<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Greedy</title>
    <script>
        //Greedy start
        function Greedy(map, startX, startY){
            if(startX == 0){
                return;
            }
            var newX = startX-1; //上一行
            var newY;
            var min;

            //TODO 3-1 start 变绿

            //3-2 计算1,2,3的差
            var left = map[newX][startY-1] - map[startX][startY]; //1
            var middle = map[newX][startY] - map[startX][startY]; //2
            var right = map[newX][startY+1] - map[startX][startY]; //3
            console.log("1,2,3差值为：" + left, middle, right);

            //TODO 将数值更新到1,2,3位置，并变换颜色

            //4-1 选择最小值
            if(left == NaN){
                min = Math.min(middle, right);
            }else if(right == NaN){
                min = Math.min(left, middle);
            }else{
                min = Math.min(left, middle, right);
            }

            //记录更新的位置
            if(min == left){
                newY = startY-1;
            }else if(min == middle){
                newY = startY;
            }else{
                newY = startY+1;
            }
            
            //TODO start变白，newY变绿，其他两个变黑

            //回传最短数值，更新后的X,Y
            return [min, newX, newY];
        }

        //map 初始化2维数组 TODO 将数值导入
        var map = [];
        var n = 40000; //随机创建数值
        for(var i=0; i<200; i++){
            map[i] = [];
            for(var j=0; j<200; j++){
                map[i][j] = n;
                n--;
            }
        }
        console.log(map);

        //total 记录最短路径数值
        var total = 0;

        //1 获取start，end
        var startX = parseInt(prompt("Start point X"));
        var startY = parseInt(prompt("Start point Y"));
        // var endX = parseInt(prompt("End point X"));
        // var endY = parseInt(prompt("End point Y"));
        console.log("用户输入起始位置：" + startX, startY);

        //记录cost和坐标，开始循环
        while(startX != 0){
            var Cost_Index = Greedy(map, startX, startY);
            total += Cost_Index[0];
            startX = Cost_Index[1];
            startY = Cost_Index[2];
            console.log("当前路径花销为" + total + "，当前坐标为" + startX, startY);
        }

        //总数值输出
        console.log("最短总数值为：" + total);
        
    </script>
</head>
<body>
    
</body>
</html>